import axios from 'axios';
import {ElNotification} from 'element-plus';
import {isNotEmpty, resolveErrorMessage, resolveErrorTitle} from '@/utils/CommonUtils';
import router from '@/router';
import store from '@/store';

const instance = axios.create({
  baseURL: window.basePathname,
  timeout: 30000,
});
export const getAction = (url, params) => {
  beforeRequest('get', url, params);
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params
    }).then(data => {
      if (beforeResolveData(data)) {
        resolve(data.data);
      }
    }).catch(error => {
      beforeRejectError(error);
      reject(error);
    });
  });
};

export const postAction = (url, data) => {
  beforeRequest('post', url, data);
  return new Promise((resolve, reject) => {
    instance.post(url, data).then(data => {
      if (beforeResolveData(data)) {
        resolve(data.data);
      }
    }).catch(error => {
      beforeRejectError(error);
      reject(error);
    });
  });
};

export const putAction = (url, data) => {
  beforeRequest('put', url, data);
  return new Promise((resolve, reject) => {
    instance.put(url, data).then(data => {
      if (beforeResolveData(data)) {
        resolve(data.data);
      }
    }).catch(error => {
      beforeRejectError(error);
      reject(error);
    });
  });
};

export const deleteAction = (url, params) => {
  beforeRequest('delete', url, params);
  return new Promise((resolve, reject) => {
    instance.delete(url, {
      params
    }).then(data => {
      if (beforeResolveData(data)) {
        resolve(data.data);
      }
    }).catch(error => {
      beforeRejectError(error);
      reject(error);
    });
  });
};

instance.interceptors.request.use((config) => {
  try {
    let userInfo = store.getters['user/userInfo'];
    if (isNotEmpty(userInfo.token)) {
      config.headers['ff-token'] = userInfo.token;
    }
  } catch (e) {
  }
  return config;
});


function beforeRequest(method, url, data) {

}

function beforeRejectError(data) {
  ElNotification({
    title: resolveErrorTitle(data),
    message: resolveErrorMessage(data),
    type: 'error',
  });
}

function beforeResolveData(data) {
  if (isNotEmpty(data) && isNotEmpty(data.data) && data.data.code + '' === '10000') {
    if (router.currentRoute.value.path !== '/login') {
      // ElNotification({
      //   title: data.data.message,
      //   type: 'warning',
      // });
      router.replace('/login');
    }
    return true;
  }

  if (!data) data = {};
  let temp = data.data;
  if (temp && !temp.success) {
    ElNotification({
      title: temp.message,
      type: 'error',
    });
    console.error(temp);
    return true;
  }

  if (data.result && data.result.success === false) {
    ElNotification({
      title: '操作失败: ' + data.result.message,
      type: 'error',
    });
    return false;
  }
  return true;
}
